using Items;
using Services;
using Skills;
using System;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class SaveData_Player
{
    public Vector3 position;
    public float powerPoint;
    public int skillPoint;
    public int money;
    public CharacterData data;
    public List<string> learnedSkills;
    public List<string> eqiupments;
    public List<string> spareWeapons;

    public SaveData_Player(InitData init)
    {
        data = init.platerInit;
        learnedSkills = init.CreateInitSkills();
        eqiupments = new List<string>();
        spareWeapons = new List<string>();
    }

    public void Save()
    {
        Player player = ServiceLocator.Get<ActionController>().player;
        EquipmentManager equipmentManager = player.EquipmentManager;
        position = player.transform.position;
        powerPoint = player.PowerPoint;
        skillPoint = player.SkillPoint;
        money = player.Money;
        data = player.defaultData;
        List<RuntimeSkill> skills = player.SkillManager.GetAllSkills();
        learnedSkills.Clear();
        foreach (RuntimeSkill run in skills)
        {
            learnedSkills.Add(run.SkillAttached.name);
        }
        eqiupments.Clear();
        foreach (Equipment equipment in equipmentManager.Equipments.Values)
        {
            eqiupments.Add(equipment.name);
        }
        spareWeapons.Clear();
        foreach (Equipment weapon in equipmentManager.SpareWeapons.Values)
        {
            spareWeapons.Add(weapon.name);
        }
    }

    public void Load()
    {
        Player player = ServiceLocator.Get<ActionController>().player;
        EquipmentManager equipmentManager = player.EquipmentManager;
        player.transform.position = position;
        player.PowerPoint = powerPoint;
        player.SkillPoint = skillPoint;
        player.Money = money;
        player.defaultData = data;
        player.SkillManager.ForgetAllSkills();
        foreach (string name in learnedSkills)
        {
            player.SkillManager.LearnSkill(name);
        }
        foreach (string name in spareWeapons)
        {
            ItemStack item = player.Bag.GetItem(name);
            if (item != null)
            {
                Equipment equipment = item.ItemAttached as Equipment;
                if (equipment != null)
                    equipmentManager.Equip(equipment);
            }
        }
        foreach (string name in eqiupments)
        {
            ItemStack item = player.Bag.GetItem(name);
            if (item != null)
            {
                Equipment equipment = item.ItemAttached as Equipment;
                if (equipment != null)
                    equipmentManager.Equip(equipment);
            }
        }
        player.SettleAllStatus(EStatusTiming.Refresh);
        player.HealthPoint = player.data.maxHP;
        player.EnergyPoint = player.data.maxEP;
        player.StatusChange?.Invoke();
    }
}